package com.leo;

import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.Scene;
import javafx.scene.control.ChoiceBox;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import javafx.util.StringConverter;

/**
 * @ClassName ChoiceBoxDemo
 * @Description
 * @Author wangss
 * @date 2020.05.24 21:32
 * @Version 1.0
 */
public class ChoiceBoxStudentDemo extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        AnchorPane anchorPane = new AnchorPane();
        anchorPane.setStyle("-fx-background-color: #e7eeea");
        Scene scene = new Scene(anchorPane);

        Student s1 = new Student("小a", 12, 99d);
        Student s2 = new Student("小b", 18, 63d);
        Student s3 = new Student("小c", 20, 60d);

        ChoiceBox<Student> choiceBox = new ChoiceBox<>();
        choiceBox.getItems().addAll(s1, s2, s3);

        choiceBox.setConverter(new StringConverter<Student>() {
            @Override
            public String toString(Student object) {
                return object.getName();
            }

            @Override
            public Student fromString(String string) {
                return null;
            }
        });

        choiceBox.setPrefWidth(200d);
        AnchorPane.setTopAnchor(choiceBox, 10d);
        AnchorPane.setLeftAnchor(choiceBox, 10d);
        anchorPane.getChildren().addAll(choiceBox);

        primaryStage.setScene(scene);
        primaryStage.setTitle("choicebox");
        primaryStage.setWidth(625d);
        primaryStage.setHeight(500d);
        primaryStage.setResizable(false);
        primaryStage.show();

        choiceBox.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<Student>() {
            @Override
            public void changed(ObservableValue<? extends Student> observable, Student oldValue, Student newValue) {
                System.out.println(newValue.toString());
            }
        });
    }
}
